package org.itboys.ace.web;

import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.itboys.admin.constant.AdminConstants;
import org.itboys.admin.dto.AdminUserDTO;
import org.itboys.admin.dto.UserRewardDTO;
import org.itboys.admin.entity.AdminRole;
import org.itboys.admin.entity.AdminUser;
import org.itboys.admin.service.AdminRoleService;
import org.itboys.admin.service.AdminUserService;
import org.itboys.admin.tools.*;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.commons.utils.time.TimeUtils;
import org.itboys.framework.query.JsonPageUtils;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mongodb.utils.page.Page;
import org.itboys.mongodb.utils.page.PageQueryParam;
import org.itboys.mongodb.utils.query.PageQueryUtils;
import org.itboys.seller.dto.SiteUserVO;
import org.itboys.seller.entity.*;
import org.itboys.seller.meta.Account;
import org.itboys.seller.meta.CashFlow;
import org.itboys.seller.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户管理
 * 
 * @author weisky
 *
 */
@RestController
@RequestMapping("/ace/admin/site")
public class AceSiteUserController extends BaseController {

	@Autowired
	private AdminUserService adminUserService;

	@Autowired
	private CaliforniaSiteUserService californiaSiteUserService;

	@Autowired
	private SiteUserEditService siteUserEditService;

	@Autowired
	private AccountService accountService;

	@Autowired
	private RankingUserService rankingUserService;

	@Autowired
	private AdminRoleService adminRoleService;

	@Autowired
	private ChangeScoreRecordService changeScoreRecordService;

	@Autowired
	private RewardRecordService rewardRecordService;
    @Resource
    private GetRewardRecordService getRewardRecordService;

	/**
	 * 修改密码
	 *
	 * @param response
	 */
	@RequestMapping("/modifyPass")
	@AdminPermissionCheck("adminUser:save")
	public void save(HttpServletRequest request, HttpServletResponse response) {
		Long userId = Long.valueOf(request.getParameter("userId"));
		String newPassword = request.getParameter("new_password");
		if (org.apache.commons.lang.StringUtils.isNotEmpty(newPassword)) {

		} else {
			newPassword = "123456";
		}
		try {
			if (userId != null) {
				californiaSiteUserService.modifyPass(userId, newPassword);
			}
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		} catch (Exception e) {
			logger.error("modify password error", e);
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}

	/**
	 * 进入我的会员列表页面
	 */
	@RequestMapping("/user-list")
	public ModelAndView myfans(Model model,HttpServletRequest request){
		LoginUser user = AdminSessionHolder.getAdminLoginUser();
		if (user.getType() != AdminConstants.TYPE_SUPER && CollectionUtils.isNotEmpty(user.getRoleIds())) {
			List<AdminRole> adminRoles = adminRoleService.getByIds(user.getRoleIds());
			if (adminRoles.size() == 1 && "查看员".equals(adminRoles.get(0).getName())) {
				model.addAttribute("readOnly", 1);
			}
		}
		return new ModelAndView("site/user-list");

	}

    /**
     * 进入上期分奖名单页面
     */
    @RequestMapping("/reward-list")
    public ModelAndView rewardList(Model model,HttpServletRequest request){
        return new ModelAndView("site/reward-list");
    }

    /**
     * 进入上期分奖名单页面
     */
    @RequestMapping("/reward-s-list")
    public ModelAndView rewardSList(Model model,HttpServletRequest request){
        return new ModelAndView("site/reward-s-list");
    }

    /**
     * 进入上期分奖名单页面
     */
    @RequestMapping("/reward-ss-list")
    public ModelAndView rewardSSList(Model model,HttpServletRequest request){
        return new ModelAndView("site/reward-ss-list");
    }

    @RequestMapping("/getRewardList")
    public void getRewardList(int type, HttpServletRequest request, HttpServletResponse response) {
        RewardRecordDB recordDB = rewardRecordService.getLastedRecord(type);
        List<UserRewardDTO> dtoList = Lists.newArrayList();
        if (recordDB != null) {
            List<Long> rankUserIds;
            if (type == 0) {
                rankUserIds = recordDB.getUserIds();
            } else if (type == 1) {
                rankUserIds = recordDB.getsUserIds();
            } else {
                rankUserIds = recordDB.getSsUserIds();
            }

            if (CollectionUtils.isEmpty(rankUserIds)) {
                AjaxUtils.renderJson(response, dtoList);
                return;
            }

            List<SiteUser> userList = californiaSiteUserService.getAdminUserByUserIds(rankUserIds);
            Map<Long, SiteUser> id2UserMap = userList.stream()
                    .collect(Collectors.toMap(SiteUser::getUserId, p -> p));
            int order = 1;
            for (Long userId : rankUserIds) {
                UserRewardDTO dto = new UserRewardDTO();
                SiteUser user = id2UserMap.get(userId);
                if (user == null) {
                    continue;
                }
                dto.setDate(TimeUtils.format(new Date(recordDB.getCt()), "yyyy-MM-dd HH:mm:ss"));
                dto.setIdCard(user.getIdCard());
                dto.setMemberName(user.getMemberName());
                dto.setRealName(user.getRealName());
                dto.setPhone(user.getPhone());
                dto.setOrder(order++);
                dtoList.add(dto);
            }
        }
        AjaxUtils.renderJson(response, dtoList);
    }

	/**
	 * 分页查询管理用户
	 *
	 * @return
	 */
	@RequestMapping("/list")
	public void list(HttpServletRequest request, HttpServletResponse response) {
		Page<SiteUserVO> page = californiaSiteUserService.pageQueryAll(request);
		JsonPageUtils.renderJsonPage(page.getTotal(),page.getTotalPages(), page.getData(), response);
	}

	/**
	 * 异步获取单个用户对象
	 *
	 * @param id
	 * @param response
	 */
	@RequestMapping("/getUser/{id}")
	public void getUser(@PathVariable("id") Long id, HttpServletResponse response) {
		SiteUser user = californiaSiteUserService.getAdminUserByUserId(id);
		AjaxUtils.renderJson(response, user);
	}

	/**
	 * 注册\修改
	 */
	@RequestMapping("/reg")
	public void regMember(@ModelAttribute SiteUserEdit user, int chargeAmount,
						  HttpServletRequest request, HttpServletResponse response) {
		SiteUser proUser = californiaSiteUserService.getAdminUserByPhone(user.getPhone());
		if (proUser != null && proUser.getUserId() != user.getUserId()) {
			AjaxUtils.renderText(response, CommonConstants.EXISTED);
			return;
		}
		if (user.getRecUserId() != 0) {
			proUser = californiaSiteUserService.getAdminUserByUserId(user.getRecUserId());
			if (proUser == null) {
				AjaxUtils.renderText(response, "推荐人不存在");
				return;
			}
		}
        if (user.getRecUserId2() != 0) {
            proUser = californiaSiteUserService.getAdminUserByUserId(user.getRecUserId2());
            if (proUser == null || proUser.getMemberType() == 0) {
                AjaxUtils.renderText(response, "第二推荐人不存在或者不是服务商身份");
                return;
            }
        }
		if (user.getUserId() == 0) {
			user.setUserId(californiaSiteUserService.genUid());
		} else {
			user.setType(1);
		}
		siteUserEditService.insert(user);

		if (chargeAmount != 0) {
			accountService.increaseToAudit(user.getUserId(), chargeAmount);
		}
		AjaxUtils.renderText(response, CommonConstants.SUCCESS);

	}

	/**
	 * 进入会员充值页面
	 */
	@RequestMapping("/toCharge")
	public ModelAndView toSiteCharge(Model model,HttpServletRequest request){
		return new ModelAndView("site/charge");

	}

	/**
	 * 进入会员充值页面
	 */
	@RequestMapping("/toScore")
	public ModelAndView toScore(Model model,HttpServletRequest request){
		return new ModelAndView("site/score");

	}

	/**
	 * 充值
	 */
	@RequestMapping("/charge")
	public void charge(long chargeUserId, int chargeAmount,
					   HttpServletRequest request,HttpServletResponse response) {
		SiteUser proUser = californiaSiteUserService.getAdminUserByUserId(chargeUserId);
		if (proUser == null) {
			AjaxUtils.renderText(response, "用户不存在");
			return;
		}
		accountService.increaseToAudit(chargeUserId, chargeAmount);
		AjaxUtils.renderText(response, CommonConstants.SUCCESS);

	}

	/**
	 * 修改积分
	 */
	@RequestMapping("/score")
	public void score(long scoreUserId, int scoreDelta,
					   HttpServletRequest request,HttpServletResponse response) {
		AdminUser adminUser = adminUserService.getById(LoginHolder.getLoginUser(WebConstants.SessionKey.ADMIN_USER).getUserid());
		if (adminUser == null) {
			AjaxUtils.renderText(response, "请重新登录");
			return;
		}
		SiteUser proUser = californiaSiteUserService.getAdminUserByUserId(scoreUserId);
		if (proUser == null) {
			AjaxUtils.renderText(response, "用户不存在");
			return;
		}
		ChangeScoreRecord changeScoreRecord = new ChangeScoreRecord();
		changeScoreRecord.setUserId(scoreUserId);
		changeScoreRecord.setScoreDelta(scoreDelta);
		changeScoreRecordService.save(changeScoreRecord);
		AjaxUtils.renderText(response, CommonConstants.SUCCESS);

	}

	/**
	 * 进入会员充值页面
	 */
	@RequestMapping("/toRankingList")
	public ModelAndView toRankingList(Model model,HttpServletRequest request){
		AdminUser proUser = adminUserService.getAdminUser("admin");
		if (proUser != null) {
			model.addAttribute("lastTotalAmount", proUser.getLastTotalAmount());
			model.addAttribute("totalAmount",proUser.getTotalAmount());
			model.addAttribute("recentTotalAmount",proUser.getRecentTotalAmount());
			model.addAttribute("rewardBalance",proUser.getRewardBalance());
			model.addAttribute("totalReward",proUser.getRewardBalance() + proUser.getRecentTotalAmount());
			model.addAttribute("accountId",proUser.getUsername());
		}
		return new ModelAndView("site/ranking-list");

	}

    @RequestMapping("/toSRankingList")
    public ModelAndView toSRankingList(Model model,HttpServletRequest request){
        AdminUser adminUser = adminUserService.getAdminUser("admin");
        if (adminUser != null) {
            model.addAttribute("lastTotalAmount", adminUser.getLastTotalAmount());
            model.addAttribute("totalAmount",adminUser.getTotalAmount());
            model.addAttribute("recentTotalAmount",adminUser.getRecentTotalAmount());
            model.addAttribute("rewardBalance",adminUser.getRewardBalanceS());
            model.addAttribute("totalReward",adminUser.getRewardBalanceS() + adminUser.getRecentTotalAmount());
            model.addAttribute("accountId",adminUser.getUsername());
        }
        return new ModelAndView("site/ranking-s-list");

    }

    /**
     * 进入会员充值页面
     */
    @RequestMapping("/toSSRankingList")
    public ModelAndView toSSRankingList(Model model,HttpServletRequest request){
        AdminUser adminUser = adminUserService.getAdminUser("admin");
        if (adminUser != null) {
            model.addAttribute("lastTotalAmount", adminUser.getLastTotalAmount());
            model.addAttribute("totalAmount",adminUser.getTotalAmount());
            model.addAttribute("recentTotalAmount",adminUser.getRecentTotalAmount());
            model.addAttribute("rewardBalance",adminUser.getRewardBalanceSS());
            model.addAttribute("totalReward",adminUser.getRewardBalanceSS() + adminUser.getRecentTotalAmount());
            model.addAttribute("accountId",adminUser.getUsername());
        }
        return new ModelAndView("site/ranking-ss-list");

    }

    @RequestMapping("/rankingList")
    public void rankingList(int type,
                            HttpServletRequest request, HttpServletResponse response) {
        RankingUserDB rankingUserDB = rankingUserService.getLatestRankingUserBySellerUserName(0, "admin");
        if (rankingUserDB == null) {
            return;
        }
        List<SiteUser> siteUserList;
        if (type == 0) {
            siteUserList = californiaSiteUserService.getAdminUserByUserIds(rankingUserDB.getUserIds());
        } else if (type == 1) {
            siteUserList = californiaSiteUserService.getAdminUserByUserIds(rankingUserDB.getsUserIds());
        } else {
            siteUserList = californiaSiteUserService.getAdminUserByUserIds(rankingUserDB.getSsUserIds());
        }

        Map<Long, SiteUser> siteUserMap = siteUserList.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));
        List<Long> userIds = siteUserList.stream().map(SiteUser::getUserId).collect(Collectors.toList());
        List<Long> recUserIds = siteUserList.stream().map(SiteUser::getRecUserId).distinct().collect(Collectors.toList());
        List<SiteUser> recSiteUsers = californiaSiteUserService.getAdminUserByUserIds(recUserIds);
        Map<Long, SiteUser> recSiteUserMap = recSiteUsers.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));
        List<Account> accounts = accountService.batchQueryAccount(userIds);
        Map<Long, Account> accountMap = accounts.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));
        Map<Long, Integer> actualScores;
        Map<Long, Integer> totalScores;
        List<Long> userIdList;
        if (type == 0) {
            actualScores = rankingUserDB.getActualScores();
            totalScores = rankingUserDB.getTotalScores();
            userIdList = rankingUserDB.getUserIds();
        } else if (type == 1) {
            actualScores = rankingUserDB.getsActualScores();
            totalScores = rankingUserDB.getsTotalScores();
            userIdList = rankingUserDB.getsUserIds();
        } else {
            actualScores = rankingUserDB.getSsActualScores();
            totalScores = rankingUserDB.getSsTotalScores();
            userIdList = rankingUserDB.getSsUserIds();
        }
        List<SiteUserVO> voList = userIdList.stream().map(userId -> {
            SiteUserVO vo = new SiteUserVO();
            SiteUser p = siteUserMap.get(userId);
            vo.setUserId(p.getUserId());
            vo.setMemberName(p.getMemberName());
            vo.setCompanyName(p.getCompanyName());
            vo.setPhone(p.getPhone());
            vo.setRecUserId(p.getRecUserId());
            vo.setRealName(p.getRealName());
            vo.setIdCard(p.getIdCard());
            Account account = accountMap.get(p.getUserId());
            if (account != null) {
                vo.setAmount(account.getAmount());
                vo.setUpdateTime(account.getUpdateTime().getTime());
            }
            SiteUser recSiteUser = recSiteUserMap.get(p.getRecUserId());
            if (recSiteUser != null) {
                vo.setRecMemberName(recSiteUser.getRealName());
            }

            Integer actualScore = actualScores.get(p.getUserId());
            Integer totalScore = totalScores.get(p.getUserId());
            vo.setActualScore(actualScore != null ? actualScore : 0);
            vo.setTotalScore(totalScore != null ? totalScore : 0);
            return vo;
        }).collect(Collectors.toList());
        JsonPageUtils.renderJsonPage(Long.valueOf(voList.size()), voList, response);
    }

	@RequestMapping("/recentRankingList")
	public void recentRankingList(HttpServletRequest request, HttpServletResponse response) {
		List<Account> accounts = accountService.getRankingUsers();
		List<Long> userIds = accounts.stream().map(Account::getUserId).collect(Collectors.toList());
		Map<Long, Account> accountMap = accounts.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));

		List<SiteUser> siteUserList = californiaSiteUserService.getAdminUserByUserIds(userIds);
		Map<Long, SiteUser> siteUserMap = siteUserList.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));
		List<SiteUserVO> voList = userIds.stream().map(userId -> {
			SiteUserVO vo = new SiteUserVO();
			SiteUser p = siteUserMap.get(userId);
			vo.setUserId(p.getUserId());
			vo.setMemberName(p.getMemberName());
			vo.setCompanyName(p.getCompanyName());
			vo.setPhone(p.getPhone());
			vo.setRecUserId(p.getRecUserId());
			vo.setRealName(p.getRealName());
			vo.setIdCard(p.getIdCard());
			Account account = accountMap.get(p.getUserId());
			if (account != null) {
				vo.setAmount(account.getAmount());
				vo.setActualScore(account.getRecentScore());
				vo.setUpdateTime(account.getUpdateTime().getTime());
			}
			return vo;
		}).collect(Collectors.toList());
		JsonPageUtils.renderJsonPage(Long.valueOf(voList.size()), voList, response);
	}

    @RequestMapping("/recentSRankingList")
    public void recentSRankingList(HttpServletRequest request, HttpServletResponse response) {
        List<Account> accounts = accountService.getSRankingUsers();
        List<Account> tmpAccountList = Lists.newArrayList();
        for (Account account : accounts) {
            if (getRewardRecordService.getByField("userId", account.getUserId()) == null) {
                tmpAccountList.add(account);
            }
        }
        List<Long> userIds = tmpAccountList.stream().map(Account::getUserId).collect(Collectors.toList());
        Map<Long, Account> accountMap = tmpAccountList.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));

        List<SiteUser> siteUserList = californiaSiteUserService.getAdminUserByUserIds(userIds);
        Map<Long, SiteUser> siteUserMap = siteUserList.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));
        List<SiteUserVO> voList = userIds.stream().map(userId -> {
            SiteUserVO vo = new SiteUserVO();
            SiteUser p = siteUserMap.get(userId);
            vo.setUserId(p.getUserId());
            vo.setMemberName(p.getMemberName());
            vo.setCompanyName(p.getCompanyName());
            vo.setPhone(p.getPhone());
            vo.setRecUserId(p.getRecUserId());
            vo.setRealName(p.getRealName());
            vo.setIdCard(p.getIdCard());
            Account account = accountMap.get(p.getUserId());
            if (account != null) {
                vo.setAmount(account.getAmount());
                vo.setActualScore(account.getRecentScoreS());
                vo.setUpdateTime(account.getUpdateTime().getTime());
            }
            return vo;
        }).collect(Collectors.toList());
        JsonPageUtils.renderJsonPage(Long.valueOf(voList.size()), voList, response);
    }

    @RequestMapping("/recentSSRankingList")
    public void recentSSRankingList(HttpServletRequest request, HttpServletResponse response) {
        List<Account> accounts = accountService.getSSRankingUsers();
        List<Long> userIds = accounts.stream().map(Account::getUserId).collect(Collectors.toList());
        Map<Long, Account> accountMap = accounts.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));

        List<SiteUser> siteUserList = californiaSiteUserService.getAdminUserByUserIds(userIds);
        Map<Long, SiteUser> siteUserMap = siteUserList.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));
        List<SiteUserVO> voList = userIds.stream().map(userId -> {
            SiteUserVO vo = new SiteUserVO();
            SiteUser p = siteUserMap.get(userId);
            vo.setUserId(p.getUserId());
            vo.setMemberName(p.getMemberName());
            vo.setCompanyName(p.getCompanyName());
            vo.setPhone(p.getPhone());
            vo.setRecUserId(p.getRecUserId());
            vo.setRealName(p.getRealName());
            vo.setIdCard(p.getIdCard());
            Account account = accountMap.get(p.getUserId());
            if (account != null) {
                vo.setAmount(account.getAmount());
                vo.setActualScore(account.getRecentScoreSs());
                vo.setUpdateTime(account.getUpdateTime().getTime());
            }
            return vo;
        }).collect(Collectors.toList());
        JsonPageUtils.renderJsonPage(Long.valueOf(voList.size()), voList, response);
    }

	/**
	 * 进入我的会员列表页面
	 */
	@RequestMapping("/user-audit")
	public ModelAndView userAudit(Model model,HttpServletRequest request){
		return new ModelAndView("site/user-audit");

	}

	/**
	 * 分页查询管理用户
	 *
	 * @return
	 */
	@RequestMapping("/auditlist")
	public void auditlist(HttpServletRequest request, HttpServletResponse response) {
		Page<SiteUserVO> page = siteUserEditService.pageQueryAll(request);
		JsonPageUtils.renderJsonPage(page.getTotal(),page.getTotalPages(), page.getData(), response);
	}

	/**
	 * 审核
	 */
	@RequestMapping(value = "/userAudit", method= RequestMethod.POST)
	public void userAudit(@RequestParam(value = "id", required = true) long id,
						  @RequestParam(value = "pass", required = false) boolean pass,
						  @RequestParam(value = "reason", required = false) String reason,
						  HttpServletRequest request, HttpServletResponse response) {
		AdminUser adminUser = adminUserService.getById(LoginHolder.getLoginUser(WebConstants.SessionKey.ADMIN_USER).getUserid());
		if (adminUser == null) {
			AjaxUtils.renderText(response, "用户不存在或已被冻结");
			return;
		}
		SiteUserEdit proUser = siteUserEditService.getById(id);
		if (proUser == null) {
			AjaxUtils.renderText(response, CommonConstants.FAIL);
			return;
		}
		proUser.setAuditState(pass ? 1 : 2);
		proUser.setAuditName(adminUser.getUsername());
		proUser.setReason(reason);
		siteUserEditService.update(proUser);
		if (!pass) {
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
			return;
		}

		if (proUser.getType() == 0) {
			SiteUser siteUser = new SiteUser();
			siteUser.setCompanyName(proUser.getCompanyName());
			siteUser.setIdCard(proUser.getIdCard());
			siteUser.setMemberName(proUser.getMemberName());
			siteUser.setPassword(proUser.getPassword());
			siteUser.setPhone(proUser.getPhone());
			siteUser.setRealName(proUser.getRealName());
			siteUser.setRecUserId(proUser.getRecUserId());
            siteUser.setRecUserId2(proUser.getRecUserId2());
			siteUser.setSellerUserName(proUser.getSellerUserName());
			siteUser.setUserId(proUser.getUserId());
            siteUser.setMemberType(proUser.getMemberType());
            siteUser.setArea(proUser.getArea());
			californiaSiteUserService.insert(siteUser);
		} else if (proUser.getType() == 1) {
			SiteUser siteUser = californiaSiteUserService.getAdminUserByUserId(proUser.getUserId());
			if (siteUser != null) {
				siteUser.setCompanyName(proUser.getCompanyName());
				siteUser.setIdCard(proUser.getIdCard());
				siteUser.setPhone(proUser.getPhone());
				siteUser.setRealName(proUser.getRealName());
				siteUser.setRecUserId(proUser.getRecUserId());
                siteUser.setRecUserId2(proUser.getRecUserId2());
                siteUser.setMemberType(proUser.getMemberType());
                siteUser.setArea(proUser.getArea());
				californiaSiteUserService.update(siteUser);
			}
		}
		AjaxUtils.renderText(response, CommonConstants.SUCCESS);

	}

	/**
	 * 进入充值记录审核页
	 */
	@RequestMapping("/charge-audit")
	public ModelAndView chargeAudit(Model model,HttpServletRequest request){
		return new ModelAndView("site/charge-audit");

	}

	/**
	 * 进入充值记录审核页
	 */
	@RequestMapping("/score-audit")
	public ModelAndView scoreAudit(Model model,HttpServletRequest request){
		return new ModelAndView("site/score-audit");

	}

	/**
	 * 进入充值历史记录页
	 */
	@RequestMapping("/charge-record")
	public ModelAndView chargeRecord(Model model,HttpServletRequest request){
		return new ModelAndView("site/charge-record");

	}

	/**
	 * 进入充值历史记录页
	 */
	@RequestMapping("/score-record")
	public ModelAndView scoreRecord(Model model,HttpServletRequest request){
		return new ModelAndView("site/score-record");

	}

	/**
	 * 分页查询充值记录
	 *
	 * @return
	 */
	@RequestMapping("/chargelist")
	public void chargelist(Integer state, String memberName, String realName, String phone, HttpServletRequest request, HttpServletResponse response) {
		List<Long> findUserIds = Lists.newArrayList();
		if (StringUtils.isNotBlank(memberName) || StringUtils.isNotBlank(realName) || StringUtils.isNotBlank(phone)) {
			List<SiteUser> findUsers = californiaSiteUserService.findUsers(memberName, realName, phone);
			if (CollectionUtils.isEmpty(findUsers)) {
				JsonPageUtils.renderJsonPage(0l,0l, Collections.emptyList(), response);
			}
			findUserIds = findUsers.stream().map(SiteUser::getUserId).collect(Collectors.toList());
		}
		PageQueryParam<T> page = (PageQueryParam<T>) PageQueryUtils
				.preparePageQueryParam(request);
		Page<CashFlow> cashFlowPage = accountService.queryCashFlow(state, findUserIds, page.getPageIndex(), page.getPageSize());

		List<Long> userIds = cashFlowPage.getData().stream().map(CashFlow::getUserId).collect(Collectors.toList());
		List<SiteUser> siteUserList = californiaSiteUserService.getAdminUserByUserIds(userIds);
		Map<Long, SiteUser> siteUserMap = siteUserList.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));
		List<Long> recUserIds = siteUserList.stream().map(SiteUser::getRecUserId).distinct().collect(Collectors.toList());
		List<SiteUser> recSiteUsers = californiaSiteUserService.getAdminUserByUserIds(recUserIds);
		Map<Long, SiteUser> recSiteUserMap = recSiteUsers.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));
		List<SiteUserVO> voList = cashFlowPage.getData().stream().filter(p -> {
			SiteUser siteUser = siteUserMap.get(p.getUserId());
			return siteUser != null;
		}).map(p -> {
			SiteUserVO vo = new SiteUserVO();
			vo.setUserId(p.getUserId());
			vo.setId(p.getId());
			SiteUser siteUser = siteUserMap.get(p.getUserId());
			if (siteUser != null) {
				vo.setMemberName(siteUser.getMemberName());
				vo.setCompanyName(siteUser.getCompanyName());
				vo.setPhone(siteUser.getPhone());
				vo.setRecUserId(siteUser.getRecUserId());
				vo.setRealName(siteUser.getRealName());
				vo.setIdCard(siteUser.getIdCard());
				SiteUser recSiteUser = recSiteUserMap.get(siteUser.getRecUserId());
				if (recSiteUser != null) {
					vo.setRecMemberName(recSiteUser.getRealName());
				}
			}
			vo.setAmount(p.getAmount());
			vo.setAuditState(p.getState());
			vo.setAuditName(p.getAuditName());
			vo.setUpdateTime(p.getUpdateTime().getTime());
			return vo;
		}).collect(Collectors.toList());
		JsonPageUtils.renderJsonPage(cashFlowPage.getTotal(),cashFlowPage.getTotalPages(), voList, response);
	}

	/**
	 * 分页查询充值记录
	 *
	 * @return
	 */
	@RequestMapping("/scorelist")
	public void scorelist(String memberName, String realName, String phone,HttpServletRequest request, HttpServletResponse response) {
		List<Long> findUserIds = Lists.newArrayList();
		if (StringUtils.isNotBlank(memberName) || StringUtils.isNotBlank(realName) || StringUtils.isNotBlank(phone)) {
			List<SiteUser> findUsers = californiaSiteUserService.findUsers(memberName, realName, phone);
			if (CollectionUtils.isEmpty(findUsers)) {
				JsonPageUtils.renderJsonPage(0l,0l, Collections.emptyList(), response);
			}
			findUserIds = findUsers.stream().map(SiteUser::getUserId).collect(Collectors.toList());
		}
		if (CollectionUtils.isNotEmpty(findUserIds)) {
			String[] userIdArray = new String[findUserIds.size()];
			for (int i = 0; i < findUserIds.size(); i++) {
				userIdArray[i] = String.valueOf(findUserIds.get(i));
			}
			request.setAttribute("filter_I_userId", userIdArray);
		}
		Page<ChangeScoreRecord> scorePage = changeScoreRecordService.pageQuery(request);

		List<Long> userIds = scorePage.getData().stream().map(ChangeScoreRecord::getUserId).collect(Collectors.toList());
		List<SiteUser> siteUserList = californiaSiteUserService.getAdminUserByUserIds(userIds);
		Map<Long, SiteUser> siteUserMap = siteUserList.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));

		List<Long> resourceUserIds = scorePage.getData().stream().map(ChangeScoreRecord::getResourceUserId).collect(Collectors.toList());
		List<SiteUser> resourceSiteUserList = californiaSiteUserService.getAdminUserByUserIds(resourceUserIds);
		Map<Long, SiteUser> resourceSiteUserMap = resourceSiteUserList.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));
		List<SiteUserVO> voList = scorePage.getData().stream().filter(p -> {
			SiteUser siteUser = siteUserMap.get(p.getUserId());
			return siteUser != null;
		}).map(p -> {
			SiteUserVO vo = new SiteUserVO();
			vo.setUserId(p.getUserId());
			vo.setId(p.getId());
			SiteUser siteUser = siteUserMap.get(p.getUserId());
			if (siteUser != null) {
				vo.setMemberName(siteUser.getMemberName());
				vo.setCompanyName(siteUser.getCompanyName());
				vo.setPhone(siteUser.getPhone());
				vo.setRecUserId(siteUser.getRecUserId());
				vo.setRealName(siteUser.getRealName());
				vo.setIdCard(siteUser.getIdCard());
			}
			vo.setScoreDelta(p.getScoreDelta());
			vo.setAuditState(p.getAuditState());
			vo.setAuditName(p.getAuditName());

			SiteUser resourceSiteUser = resourceSiteUserMap.get(p.getResourceUserId());
			if (resourceSiteUser != null) {
				vo.setResourceName(p.getUserId() == p.getResourceUserId() ? "本人" : resourceSiteUser.getRealName());
				vo.setResourcePhone(resourceSiteUser.getPhone());
			}
			vo.setUpdateTime(p.getUt());
			return vo;
		}).collect(Collectors.toList());
		JsonPageUtils.renderJsonPage(scorePage.getTotal(),scorePage.getTotalPages(), voList, response);
	}

	/**
	 * 充值审核
	 */
	@RequestMapping(value = "/chargeAudit", method= RequestMethod.POST)
	public void chargeAudit(@RequestParam(value = "cashflowId", required = true) long cashflowId,
						  @RequestParam(value = "pass", required = false) boolean pass,
							@RequestParam(value = "reason", required = false) String reason,
						  HttpServletRequest request, HttpServletResponse response) {
		AdminUser adminUser = adminUserService.getById(LoginHolder.getLoginUser(WebConstants.SessionKey.ADMIN_USER).getUserid());
		if (adminUser == null) {
			AjaxUtils.renderText(response, "用户不存在或已被冻结");
			return;
		}
		boolean result = accountService.audit(cashflowId, pass, reason, adminUser.getUsername());
		if (!result) {
			AjaxUtils.renderText(response, CommonConstants.FAIL);
			return;
		}
		AjaxUtils.renderText(response, CommonConstants.SUCCESS);

	}

	/**
	 * 充值审核
	 */
	@RequestMapping(value = "/scoreAudit", method= RequestMethod.POST)
	public void scoreAudit(@RequestParam(value = "recordId", required = true) long recordId,
							@RequestParam(value = "pass", required = false) boolean pass,
							@RequestParam(value = "reason", required = false) String reason,
							HttpServletRequest request, HttpServletResponse response) {
		AdminUser adminUser = adminUserService.getById(LoginHolder.getLoginUser(WebConstants.SessionKey.ADMIN_USER).getUserid());
		if (adminUser == null) {
			AjaxUtils.renderText(response, "请重新登录");
			return;
		}
		ChangeScoreRecord changeScoreRecord = changeScoreRecordService.getById(recordId);
		if (changeScoreRecord == null) {
			AjaxUtils.renderText(response, CommonConstants.FAIL);
			return;
		}
		changeScoreRecord.setAuditState(pass ? 1 : 2);
		changeScoreRecord.setAuditName(adminUser.getUsername());
		changeScoreRecord.setReason(reason);
		changeScoreRecordService.update(changeScoreRecord);
		if (!pass) {
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
			return;
		}

		accountService.updateScore(changeScoreRecord.getUserId(), changeScoreRecord.getScoreDelta());
		AjaxUtils.renderText(response, CommonConstants.SUCCESS);

	}

	/**
	 * 提交冻结待审核
	 */
	@RequestMapping("/freeze/{userId}")
	public void freeze(@PathVariable("userId") Long userId, HttpServletResponse response) {
		SiteUser siteUser = californiaSiteUserService.getAdminUserByUserId(userId);
		if (siteUser == null) {
			AjaxUtils.renderText(response, CommonConstants.FAIL);
			return;
		}
		SiteUserEdit proUser = new SiteUserEdit();
		proUser.setCompanyName(siteUser.getCompanyName());
		proUser.setIdCard(siteUser.getIdCard());
		proUser.setMemberName(siteUser.getMemberName());
		proUser.setPassword(siteUser.getPassword());
		proUser.setPhone(siteUser.getPhone());
		proUser.setRealName(siteUser.getRealName());
		proUser.setRecUserId(siteUser.getRecUserId());
		proUser.setSellerUserName(siteUser.getSellerUserName());
		proUser.setUserId(siteUser.getUserId());
		proUser.setType(2);
		siteUserEditService.insert(proUser);
	}

	/**
	 * 提交解冻待审核
	 */
	@RequestMapping("/unfreeze/{userId}")
	public void unfreeze(@PathVariable("userId") Long userId, HttpServletResponse response) {
		SiteUser siteUser = californiaSiteUserService.getAdminUserByUserId(userId);
		if (siteUser == null) {
			AjaxUtils.renderText(response, CommonConstants.FAIL);
			return;
		}
		SiteUserEdit proUser = new SiteUserEdit();
		proUser.setCompanyName(siteUser.getCompanyName());
		proUser.setIdCard(siteUser.getIdCard());
		proUser.setMemberName(siteUser.getMemberName());
		proUser.setPassword(siteUser.getPassword());
		proUser.setPhone(siteUser.getPhone());
		proUser.setRealName(siteUser.getRealName());
		proUser.setRecUserId(siteUser.getRecUserId());
		proUser.setSellerUserName(siteUser.getSellerUserName());
		proUser.setUserId(siteUser.getUserId());
		proUser.setType(3);
		siteUserEditService.insert(proUser);
	}

	/**
	 * 进入冻结审核页面
	 */
	@RequestMapping("/user-frozen")
	public ModelAndView userFrozen(Model model,HttpServletRequest request){
		return new ModelAndView("site/user-freeze-audit");

	}

	/**
	 * 审核
	 */
	@RequestMapping(value = "/userFreezeAudit", method= RequestMethod.POST)
	public void userFreezeAudit(@RequestParam(value = "id", required = true) long id,
						  @RequestParam(value = "pass", required = false) boolean pass,
								@RequestParam(value = "reason", required = false) String reason,
						  HttpServletRequest request, HttpServletResponse response) {
		AdminUser adminUser = adminUserService.getById(LoginHolder.getLoginUser(WebConstants.SessionKey.ADMIN_USER).getUserid());
		if (adminUser == null) {
			AjaxUtils.renderText(response, "用户不存在或已被冻结");
			return;
		}
		SiteUserEdit proUser = siteUserEditService.getById(id);
		if (proUser == null) {
			AjaxUtils.renderText(response, CommonConstants.FAIL);
			return;
		}
		proUser.setAuditState(pass ? 1 : 2);
		proUser.setAuditName(adminUser.getUsername());
		proUser.setReason(reason);
		siteUserEditService.update(proUser);
		if (!pass) {
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
			return;
		}

		californiaSiteUserService.freezeByUserId(proUser.getUserId(), proUser.getType() == 2 ? true : false);
		accountService.freezeByUserId(proUser.getUserId(), proUser.getType() == 2 ? true : false);
		AjaxUtils.renderText(response, CommonConstants.SUCCESS);

	}

	/**
	 * 进入充值历史记录页
	 */
	@RequestMapping("/cleanScore-record")
	public ModelAndView cleanScoreRecord(Model model,HttpServletRequest request){
		return new ModelAndView("site/cleanScore-record");

	}

	/**
	 * 分页查询充值记录
	 *
	 * @return
	 */
	@RequestMapping("/cleanScorelist")
	public void cleanScorelist(String memberName, String realName, String phone,HttpServletRequest request, HttpServletResponse response) {
		List<Long> findUserIds = Lists.newArrayList();
		if (StringUtils.isNotBlank(memberName) || StringUtils.isNotBlank(realName) || StringUtils.isNotBlank(phone)) {
			List<SiteUser> findUsers = californiaSiteUserService.findUsers(memberName, realName, phone);
			if (CollectionUtils.isEmpty(findUsers)) {
				JsonPageUtils.renderJsonPage(0l,0l, Collections.emptyList(), response);
			}
			findUserIds = findUsers.stream().map(SiteUser::getUserId).collect(Collectors.toList());
		}
		if (CollectionUtils.isNotEmpty(findUserIds)) {
			String[] userIdArray = new String[findUserIds.size()];
			for (int i = 0; i < findUserIds.size(); i++) {
				userIdArray[i] = String.valueOf(findUserIds.get(i));
			}
			request.setAttribute("filter_I_userId", userIdArray);
		}
		Page<RewardRecordDB> scorePage = rewardRecordService.pageQuery(request);

		List<Long> userIds = Lists.newArrayList();
		for (RewardRecordDB rewardRecordDB : scorePage.getData()) {
			List<Long> rewardUserIds = rewardRecordDB.getUserIds();
            if (CollectionUtils.isNotEmpty(rewardUserIds)) {
                userIds.addAll(rewardUserIds);
            }
		}
		List<SiteUser> siteUserList = californiaSiteUserService.getAdminUserByUserIds(userIds);
		Map<Long, SiteUser> siteUserMap = siteUserList.stream().collect(Collectors.toMap(p -> p.getUserId(), p -> p));

		List<SiteUserVO> voList = Lists.newArrayList();
		for (RewardRecordDB rewardRecordDB : scorePage.getData()) {
			Map<Long, Integer> cleanScoreMap = rewardRecordDB.getCleanScoreMap();
            if (CollectionUtils.isEmpty(rewardRecordDB.getUserIds())) {
                continue;
            }
			for (Long userId : rewardRecordDB.getUserIds()) {
				SiteUserVO vo = new SiteUserVO();
				vo.setUserId(userId);
				SiteUser siteUser = siteUserMap.get(userId);
				if (siteUser != null) {
					vo.setMemberName(siteUser.getMemberName());
					vo.setCompanyName(siteUser.getCompanyName());
					vo.setPhone(siteUser.getPhone());
					vo.setRecUserId(siteUser.getRecUserId());
					vo.setRealName(siteUser.getRealName());
					vo.setIdCard(siteUser.getIdCard());
				}
				vo.setUpdateTime(rewardRecordDB.getCt());
				vo.setCleanScore(cleanScoreMap.get(userId) != null ? cleanScoreMap.get(userId) : 0);
				voList.add(vo);
			}
		}
		JsonPageUtils.renderJsonPage(scorePage.getTotal(),scorePage.getTotalPages(), voList, response);
	}
}
